<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-operator">
        <a-button type="primary" icon="plus" >新增</a-button>
        <a-button type="primary" icon="reload" >导出</a-button>
        <a-button type="primary" icon="reload" >导入</a-button>
        <!-- 高级查询区域 -->
        <j-super-query :fieldList="fieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
    </div>
    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon" />
        已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>
        项
        <a style="margin-left: 24px"  @click="onClearSelected">清空</a>
        <span style="float:right;">
          <a><a-icon type="sync" />刷新</a>
          <a-divider type="vertical" />
          <col-setting v-if="colSettingList.length>0" :defColumns="colSettingList" @columnsSetting="columnsSetting" />
        </span>
      </div>
      <a-table
        size="middle"
        bordered
        :rowKey="(record, index) => index"
        :columns="columns"
        :data-source="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :row-selection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange"
      >
        <template slot="switch" slot-scope="text">
          <a-switch :checked="text" :disabled="true" />
        </template>
        <template slot="#" slot-scope="text,record,i">
          <span>{{i+1}}</span>
        </template>
        <template slot="uploadImg" slot-scope="list">
          <div class="j-table-slot-view">
            <img :src="list[0].url" :preview="dataSource[0].key" />
          </div>
        </template>
        <template slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多<a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a >提交流程</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a >删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
      </a-table>
    </div>
  </a-card>
</template>
<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import ColSetting from '@/components/custom/ColSetting'
import JSuperQuery from '@/components/jeecg/JSuperQuery.vue'
import { getAction } from '@/api/manage'
export default {
  name: 'ProcessList',
  components: {
    ColSetting,
    JSuperQuery
  },
  mixins: [JeecgListMixin],
  data() {
    return {
      columns: [], // 页面表格列
      colSettingList: [], // 表格列设置
      defColumns: [// 默认表头
        {
          title: '#',
          dataIndex: 'rowIndex',
          width: 60,
          align: 'center',
          fixed: 'left',
          scopedSlots: { customRender: '#' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/activiti/formData/list',
        deleteBatch: '/diagram/diagramConfiguration/deleteBatch',
        delete: '/diagram/diagramConfiguration/delete',
        importExcelUrl: '/sys/fillRule/importExcel',
        exportXlsUrl: '/sys/fillRule/exportXls',
        getKfdJson: '/activiti/form/getFormByModelId' // 自定义表单查询
      },
      fullscreen: true,
      fieldList: [],
      id: '', // 流程id
      disableMixinCreated: true, // 禁止mixin自动加载
      desformDesignList: []// 表单设计器组件list（排除布局组件）
    }
  },
  watch: {
    $route() {
      this.init()
    }
  },
  created() {
    this.init()
    this.queryParam.modelId = this.id
    this.loadData()
    this.initDictConfig()
  },
  methods: {
    init() {
      const id = this.$route.fullPath.replace('/processList/', '')
      if (!id) {
        this.$message.warning('未找到需要查询的流程ID')
        return false
      }
      this.id = id
      this.getFormJson(id).then((res) => { // 查询已有表单设计器
        if (res.success) {
          const formData = res.result ? JSON.parse(res.result.htmlJson) : []
          this.desformDesignList = this.getFormList(formData.list)
          this.setSuperQueryFieldList()
          this.setColumns()
        } else {
          this.$message.warning(res.message)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams()// 查询条件
      this.loading = true
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records
          this.dataSource.forEach((item) => {
            item.formData = JSON.parse(item.formData)
          })
          this.ipagination.total = res.result.total
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    getFormJson(id) {
      return getAction(this.url.getKfdJson, { modelId: id })
    },
    handleEdit() {

    },
    importExcelUrl() {
      return `${window._CONFIG['domianURL']}${this.url.importExcelUrl}`
    },
    columnsSetting(checkedValues) { // 根据配置的colunms 渲染表格
      this.columns = this.colSettingList.filter(item => {
        if (checkedValues.indexOf(item.dataIndex) >= 0) {
          return true
        }
        return false
      })
    },
    getFormList(data) { // 根据表单设计器json获取组件（不包含布局容器）
      let formList = []
      data.forEach(item => {
        if (item.model && item.type !== 'batch') {
          formList.push(item)
        } else if (item.type === 'card') {
          formList = formList.concat(this.getFormList(item.list))
        } else if (item.type === 'grid') {
          item.columns.forEach(element => {
            formList = formList.concat(this.getFormList(element.list))
          })
        } else if (item.type === 'table') {
          item.trs.forEach(tr => {
            tr.tds.forEach(td => {
              formList = formList.concat(this.getFormList(td.list))
            })
          })
        }
      })
      return formList
    },
    setSuperQueryFieldList() {
      const superQueryFieldList = []
      this.desformDesignList.forEach(item => {
        const obj = {
          type: 'string',
          value: item.model,
          text: item.label
        }
        if (item.type === 'number' || item.type === 'date') {
          obj.type = item.type
        } else if (item.type === 'time') {
          obj.type = 'datetime'
        } else if (item.type === 'user') {
          obj.type = 'select-user'
        } else if (item.type === 'dept') {
          obj.type = 'select-depart'
        } else if (item.type === 'select') {
          obj.type = 'select'
          obj.options = item.options.options
        }
        superQueryFieldList.push(obj)
      })
      this.fieldList = superQueryFieldList
    },
    setColumns() {
      this.columns = []
      this.columns.push(this.defColumns[0])
      const that = this
      this.desformDesignList.forEach(item => {
        const key = item.model ? item.model : item.key
        const slots = ['switch', 'uploadImg'].indexOf(item.type) >= 0 ? item.type : 'text'
        that.columns.push({
          title: item.label,
          align: 'center',
          dataIndex: 'formData.' + key,
          scopedSlots: { customRender: slots }
        })
      })
      this.columns.push(this.defColumns[1])
      this.colSettingList = JSON.parse(JSON.stringify(this.columns))
      console.log(this.columns)
    }
  }
}
</script>
<style scoped>
  /* @import '~@assets/less/common.less'; */
  .j-table-slot-view{
    font-size: 12px;
    font-style: italic;
  }
  .j-table-slot-view img {
    max-width: 80px;
    max-height: 25px;
  }
</style>
